import { useMemberStore } from "@/stores"

// 基地址
const baseURL = 'http://127.0.0.1:5173'
// const baseURL = window.location.origin

// 添加拦截器
const httpInterceptor = {
    invoke(options: UniApp.RequestOptions) {
        if (!options.url.startsWith('http')) {
            options.url = baseURL + options.url
        }
        options.timeout = 10000

        options.header = {
            ...options.header,
            'source-client': 'app',
            'Content-type': 'application/json'
        }
        // options.header.Authorization = 'eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTEzNTM4ODQsInVzZXJJZCI6Mn0.bw7dXyTsgCmD3i9C6EBU2PlZWXd3mezhMaLy8JXlZr0'
    }
}

// 使用拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)


// 请求函数封装
export const http = (options: UniApp.RequestOptions) => {
    return new Promise((resolve, reject) => {
        uni.request({
            ...options,
            success(res) {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    resolve(res.data)
                } else if (res.statusCode === 401) {
                    const memberStore = useMemberStore()
                    memberStore.clearProfile()
                    uni.navigateTo({ url: '/pages/login/login' })
                    reject(res)
                } else {
                    uni.showToast({
                        icon: 'error',
                        title: (res.data).msg || '请求错误',
                        mask: true
                    })
                    reject(res)
                }
            },
            fail(err) {
                uni.showToast({
                    icon: 'error',
                    title: '网络错误',
                    mask: true
                })
                reject(err)
            }
        })
    })
}
